package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public void save(Order order) {
        //为了凑齐order和order_detail中得数据,需要从下面取数据
        //ThreadLocal  userid    user_name
        //购物车        订单总金额 = 各个购物项*数量   再相加
        //默认地址      电话  收货人   地址信息

        //1. 获取登录用户信息
        User user = UserHolder.get();

        //2. 获取到当前用户的购物项列表
        List<Cart> cartList = cartService.findList();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("当前用户购物中没有任何菜品,无法生成订单");
        }

        //3. 根据传入地址id获取地址
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("当前用户地址不存在,请检查");
        }

        //4. 使用雪花算法提前生成订单id
        long orderId = IdWorker.getId();//mybatisplus提供的方法

        //声明总金额,初始化为0   double total = 0;
        BigDecimal total = new BigDecimal(0);

        //5. 组装OrderDetail对象, 保存到order_detail表
        for (Cart cart : cartList) {

            //5-1 凑齐OrderDetail属性
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());

            //5-2 保存
            orderDetailMapper.insert(orderDetail);

            //5-3 总金额+=数量*单价   total+=number*amount;
            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        //6. 组装Order对象,保存到orders表
        //6-1 凑齐order属性
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));//订单号
        order.setStatus(1);//订单状态初始化为1待付款
        order.setUserId(user.getId());
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//todo 应该是支付的时候设置
        order.setAmount(total);//当前订单总金额=订单详情中number*amount  再相加
        order.setUserName(user.getName());//登录用户username
        order.setPhone(address.getPhone());//手机
        order.setAddress(address.getDetail());//收货地址
        order.setConsignee(address.getConsignee());//收货人

        //6-2 保存
        orderMapper.insert(order);

        //7 清空购物车
        cartService.cleanList();
    }

    @Override
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
    public Page<Order> findByPage(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getNumber, number);
        wrapper.between(Order::getCheckoutTime, beginTime, endTime);

        Page<Order> orderPage = new Page<>(pageNum, pageSize);
        orderPage = orderMapper.selectPage(orderPage, wrapper);

        return orderPage;
    }

    @Override
    public Page<Order> findNewPage(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, UserHolder.get().getId());
        wrapper.orderByDesc(Order::getCheckoutTime);

        Page<Order> orderPage = new Page<>(pageNum, pageSize);
        orderMapper.selectPage(orderPage, wrapper);

        List<Order> orderList = orderPage.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {

                //4.根据菜品的id从口味表中查询口味列表
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }

        return orderPage;
    }


}
